package utils

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type BarrageClaims struct {
	jwt.RegisteredClaims
}

func CreateToken(signingKey string) string {
	mySigningKey := []byte(signingKey)
	claims := BarrageClaims{
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			Issuer:    "MonkeyBrother",
			Subject:   "go-barrage",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, _ := token.SignedString(mySigningKey)
	return ss
}

func ParseToken(tokenString string, signingKey string) (*BarrageClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &BarrageClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(signingKey), nil
	})
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	if claims, ok := token.Claims.(*BarrageClaims); ok && token.Valid {
		return claims, nil
	} else {
		fmt.Println(err)
		return nil, err
	}

}
